package cn.enine.tbcharge.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.zyao89.view.zloading.ZLoadingDialog;
import com.zyao89.view.zloading.Z_TYPE;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

import cn.enine.tbcharge.R;
import cn.enine.tbcharge.adapter.CommonAdapter;
import cn.enine.tbcharge.adapter.ViewHolder;
import cn.enine.tbcharge.base.MyBaseActivity;
import cn.enine.tbcharge.pojo.AppSfMain;
import cn.enine.tbcharge.pojo.AppXmpy;
import cn.enine.tbcharge.pojo.RetMsg;
import cn.enine.tbcharge.util.DateConvert;
import cn.enine.tbcharge.util.HttpUrl;
import cn.enine.tbcharge.util.MyToastUtil;
import cn.enine.tbcharge.util.NetWorkUtils;
import cn.enine.tbcharge.util.SharedPreferencesUtils;
import cn.enine.tbcharge.util.StringUtils;
import cn.enine.tbcharge.util.UserClient;
import cn.enine.tbcharge.view.XListView;

public class XmlistActivity extends MyBaseActivity {

    XListView listView;
    //标题
    TextView title, uname;
    LinearLayout back;
    ZLoadingDialog dialog;//加载动画
    Context con = XmlistActivity.this;
    private int pageNum1 = 1;// 无关键字页数
    List<AppXmpy> list;
    private ImageView searchBtn;
    private EditText key;

    @Override
    protected void initUI() {
        setContentView(R.layout.activity_sflist);
        searchBtn = (ImageView) findViewById(R.id.cxButton);
        searchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getInfo();
            }
        });
        key = (EditText) findViewById(R.id.key);
        key.setHint("请输入拼音码");
        key.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
        key .setImeOptions(EditorInfo.IME_ACTION_DONE);
        title = (TextView) findViewById(R.id.title);
        uname = (TextView) findViewById(R.id.uname);
        title.setText("收费项目");
        uname.setText("");
        uname.setVisibility(View.VISIBLE);
        back = (LinearLayout) findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        listView = (XListView) findViewById(R.id.listView);
        listView.setPullLoadEnable(true);
        dialog = new ZLoadingDialog(con);
        dialog.setLoadingBuilder(Z_TYPE.DOUBLE_CIRCLE)//设置类型
                .setLoadingColor(Color.parseColor("#1C86EE"))//颜色
                .setHintText("Loading...")
                .setHintTextSize(16) // 设置字体大小 dp
                .setHintTextColor(Color.parseColor("#1C86EE"));  // 设置字体颜色
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if(NetWorkUtils.isNetworkConnected(con)) {//联网状态
                    Bundle b = new Bundle();
                    b.putSerializable("b", list.get(i - 1));
                    startActivity(new Intent(con, XmaddActivity.class).putExtras(b).putExtra("type", "edit"));
                }else{
                    MyToastUtil.ShowToast(con, "网络异常，禁止编辑");
                }
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        if(NetWorkUtils.isNetworkConnected(con)){//联网状态
            getInfo();
        }else{
            list = LitePal.findAll(AppXmpy.class);
            Log.i("本地list","size====="+list.size());
            listView.setPullLoadEnable(false);
            listView.setPullRefreshEnable(false);
            listView.setAdapter(new CommonAdapter(con, list, R.layout.sf_main_item) {
                @Override
                public void convert(ViewHolder helper, Object item) {
                    if (item instanceof AppXmpy) {
                        AppXmpy appXmpyItem = (AppXmpy) item;
                        helper.setText(R.id.xm, "项目名称:"+appXmpyItem.getYyxmmc());
                        helper.setText(R.id.jkdah, "拼音码:"+appXmpyItem.getSzm());
                        helper.setText(R.id.sfrq, "项目编码:"+appXmpyItem.getYyxmbm()+"  ");
                    }
                }
            });
        }
    }

    @Override
    protected void initListener() {

    }

    public void getInfo() {
        RequestParams ps = new RequestParams();
        ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
        ps.add("type", "2");
        ps.add("page", pageNum1 + "");
        ps.add("flag", "0");
        if (!StringUtils.isEmpty(key.getText().toString()))
            ps.add("xmmc", key.getText().toString());
        UserClient.get(HttpUrl.GetXmList, ps, new AsyncHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
            }
            @Override
            public void onFailure(int statusCode, Throwable error, String content) {
                super.onFailure(statusCode, error, content);
                MyToastUtil.ShowToast(con, "请求失败");
            }
            @Override
            public void onSuccess(String content) {
                super.onSuccess(content);
                dialog.dismiss();
                RetMsg ret = JSON.parseObject(content, RetMsg.class);
                if (ret.getCode().equals("200")) {
                    List<AppXmpy> ll = JSON.parseArray(ret.getList(), AppXmpy.class);
                    if (pageNum1 == 1)
                        list = new ArrayList<AppXmpy>();
                    for (int i = 0; i < ll.size(); i++) {
                        AppXmpy AppXmpy = ll.get(i);
                        list.add(AppXmpy);
                    }
                    for (int i = 0; i < ll.size(); i++) {
                        AppXmpy appXmpy = ll.get(i);
                        List<AppXmpy> jlist = LitePal.where("nid = ?", appXmpy.getId()+"").order("nid").find(AppXmpy.class);
                        if (jlist.size() > 0) {
                            Log.i("测试数据", "删除后插入的数据");
                            jlist.get(0).delete();
                            appXmpy.setNid(appXmpy.getId()+"");
                            appXmpy.save();
                        } else {
                            Log.i("测试数据", "直接插入的数据");
                            appXmpy.save();
                        }
                    }
                    listView.setSelection(list.size() - ll.size());
                    listView.stopRefresh();
                    listView.stopLoadMore();
                    listView.setRefreshTime("刚刚");
                    int totalPage = Integer.parseInt(ret.getTotalPage());
                    listView.setPullLoadEnable(totalPage<=1 ? false : true);
                    listView.setXListViewListener(new XListView.IXListViewListener() {
                        @Override
                        public void onRefresh() {
                            pageNum1 = 1;
                            getInfo();
                        }
                        @Override
                        public void onLoadMore() {
                            pageNum1 = pageNum1 + 1;
                            getInfo();
                        }
                    });
                    listView.setAdapter(new CommonAdapter(con, list, R.layout.sf_main_item) {
                        @Override
                        public void convert(ViewHolder helper, Object item) {
                            if (item instanceof AppXmpy) {
                                AppXmpy appXmpyItem = (AppXmpy) item;
                                helper.setText(R.id.xm, "项目名称:"+appXmpyItem.getYyxmmc());
                                helper.setText(R.id.jkdah, "拼音码:"+appXmpyItem.getSzm());
                                helper.setText(R.id.sfrq, "项目编码:"+appXmpyItem.getYyxmbm()+"  ");
                            }
                        }
                    });
                } else {
                    MyToastUtil.ShowToast(con, "获取错误");
                }
            }
        });
    }
}
